import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:tray_manager/tray_manager.dart';
import 'package:window_manager/window_manager.dart';
import 'package:windows_demo/Utils/color_utils.dart';
import 'package:windows_demo/setting.dart';

import 'Widgets/BarItem.dart';
import 'Widgets/leftNavigationBar.dart';
import 'chat/chat.dart';

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> with WindowListener,TrayListener {

  final List pages = [
    const Chat(),
    const Setting(title: '2',),
    const Setting(title: '3',),
  ];
  int selectedIndex = 0;
  PageController pageController = PageController(initialPage: 0);

  final List navigationItemsInfo = [
    NavigationItemInfo(
      label: '消息',
      icon: 'assets/images/dialog_unselect.png',
      activeIcon: 'assets/images/dialog_select.png',
      width: 16,
      height: 16,
    ),
    NavigationItemInfo(
      label: '工作台',
      icon: 'assets/images/work_unselect.png',
      activeIcon: 'assets/images/work_select.png',
      width: 16,
      height: 16,
    ),
    NavigationItemInfo(
      label: '设置',
      icon: 'assets/images/setting_unselect.png',
      activeIcon: 'assets/images/setting_select.png',
      width: 16,
      height: 16,
    ),
  ];

  bool _hasIcon = false;
  Timer? _timer;
  final String _iconPathWin = 'assets/images/icon.ico';
  final String _iconPathOther = 'assets/images/icon.png';
  final String _iconNullWin = '';
  final String _iconNullOther = '';

  bool isMaximized = false;
  bool isAlwaysOnTop = false;

  @override
  void initState() {
    super.initState();
    init();
  }

  /// 初始化
  init() async {
    closeIconFlash();

    trayManager.addListener(this);

    windowManager.addListener(this);
    setPreventClose();
  }

  /// 任务栏图标闪烁
  iconFlash() {
    if (_timer != null && _timer!.isActive) {
      return;
    }
    _timer = Timer.periodic(const Duration(milliseconds: 500), (timer) async {
      if (_hasIcon) {
        await trayManager.setIcon(Platform.isWindows ? _iconNullWin : _iconNullOther);
      } else {
        await trayManager.setIcon(Platform.isWindows ? _iconPathWin : _iconPathOther);
      }
      _hasIcon = !_hasIcon;
    });
  }

  /// 任务栏图标闪烁取消
  closeIconFlash() async {
    if (_timer != null && _timer!.isActive) {
      _timer?.cancel();
    }
    await trayManager.setIcon(Platform.isWindows ? _iconPathWin : _iconPathOther);
    _hasIcon = true;
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: DragToResizeArea(
          resizeEdgeSize: 2,
          child: buildBody(),
        ),
      ),
    );
  }

  buildBody() {
    return Container(
      color: YZMColors.color_primary_10,
      child: Column(
        children: [
          DragToMoveArea(
            child: Row(
              children: [
                Builder(builder: (context) {
                  return GestureDetector(
                    // onPanStart和onDoubleTap设置空点击事件，防止触发背景的拖动和双击放大事件
                    onPanStart: (details) {},
                    onDoubleTap: (){},
                    onTap: () {
                      SmartDialog.showAttach(
                        targetContext: context,
                        usePenetrate: true,
                        useAnimation: false,
                        keepSingle: true,
                        builder: (_) {
                          return Container(
                            margin: const EdgeInsets.only(left: 5),
                            width: 200,
                            height: 500,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(4),
                              color: YZMColors.color_black_40,
                            ),
                          );
                        },
                      );
                    },
                    child: Container(
                      margin: const EdgeInsets.all(5),
                      padding: const EdgeInsets.all(5),
                      decoration: BoxDecoration(
                        color: YZMColors.color_primary,
                        borderRadius: BorderRadius.circular(4),
                      ),
                      child: const Text(
                        '刘克',
                        style: TextStyle(
                          color: YZMColors.color_white,
                        ),
                      ),
                    ),
                  );
                }),
                const Expanded(child: SizedBox.shrink()),
                Row(
                  children: [
                    BarItem(
                      icon: isAlwaysOnTop ? 'assets/images/unpin.png' : 'assets/images/top.png',
                      onTap: () {
                        setState(() {
                          windowManager.setAlwaysOnTop(!isAlwaysOnTop);
                          isAlwaysOnTop = !isAlwaysOnTop;
                        });
                      },
                    ),
                    BarItem(
                      icon: 'assets/images/minimize.png',
                      onTap: () {
                        windowManager.minimize();
                      },
                    ),
                    BarItem(
                      icon: isMaximized ? 'assets/images/unMaximize.png' : 'assets/images/maximize.png',
                      onTap: () {
                        setState(() {
                          isMaximized ? windowManager.unmaximize() : windowManager.maximize();
                          isMaximized = !isMaximized;
                        });
                      },
                    ),
                    BarItem(
                      icon: 'assets/images/shut_down.png',
                      onTap: () {
                        windowManager.close();
                      },
                    )
                  ],
                ),
              ],
            ),
          ),
          Expanded(
            child: Row(
              children: [
                LeftNavigationBar(
                  navigationItemsInfo: navigationItemsInfo,
                  selectedIndex: selectedIndex,
                  onSelect: (index) {
                    setState(() {
                      selectedIndex = index;
                      pageController.jumpToPage(index);
                    });
                  },
                ),
                Expanded(
                  child: PageView.builder(
                    physics: const NeverScrollableScrollPhysics(),
                    controller: pageController,
                    itemCount: pages.length,
                    itemBuilder: (context, index) => pages[index],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    _timer?.cancel();
    trayManager.removeListener(this);
    windowManager.removeListener(this);
    super.dispose();
  }

  @override
  Future<void> onTrayIconMouseDown() async {
    closeIconFlash();
    windowManager.show();
  }

  @override
  Future<void> onTrayIconRightMouseDown() async {
    Menu menu = Menu(
      items: [
        MenuItem(
          key: 'flash',
          label: '图标闪烁',
          onClick: (menuItem) {
            iconFlash();
          },
        ),
        MenuItem.separator(),
        MenuItem(
          key: 'closeFlash',
          label: '图标闪烁取消',
          onClick: (menuItem) {
            closeIconFlash();
          },
        ),
        MenuItem.separator(),
        MenuItem(
          key: 'toast',
          label: 'Toast',
          onClick: (menuItem) {
            windowManager.show();
            SmartDialog.showToast('Toast');
          },
        ),
        MenuItem.separator(),
        MenuItem(
          key: 'exit_app',
          label: '退出应用',
          onClick: (menuItem) {
            windowManager.show();
            windowManager.close();
          },
        ),
      ],
    );
    await trayManager.setContextMenu(menu);
    trayManager.popUpContextMenu();
  }

  setPreventClose() async {
    await windowManager.setPreventClose(true);
    setState(() {});
  }

  @override
  void onWindowClose() async {
    bool isPreventClose = await windowManager.isPreventClose();
    if (isPreventClose) {
      SmartDialog.show(builder: (_) {
        return Container(
          width: 300,
          height: 170,
          alignment: Alignment.center,
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(20),
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              const Text('确认关闭应用？'),
              Wrap(
                spacing: 20,
                children: [
                  ElevatedButton(
                    onPressed: () async {
                      SmartDialog.dismiss();
                      await windowManager.destroy();
                    },
                    child: const Text('确认'),
                  ),
                  ElevatedButton(
                    onPressed: () {
                      SmartDialog.dismiss();
                    },
                    child: const Text('取消'),
                  )
                ],
              )
            ],
          ),
        );
      });
    }
  }

  @override
  void onWindowEvent(String eventName) {
    SmartDialog.dismiss();
  }
}